package com.jichangxiu.framework.filter;

import cn.hutool.core.util.StrUtil;
import com.jichangxiu.common.cache.RedisService;
import com.jichangxiu.common.constant.ErrorCode;
import com.jichangxiu.common.constant.RedisKeys;
import com.jichangxiu.common.exception.CaptchaException;
import com.jichangxiu.common.properties.JcxProperties;
import com.jichangxiu.framework.security.handler.LoginFailureHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CaptchaFilter:
 *
 * @author Jcx
 * @create 2023-04-04 13:31
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Resource
    private JcxProperties jcxProperties;

    @Resource
    private RedisService redisService;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (jcxProperties.getLoginProperties().getLoginProcessingUrl().equals(httpServletRequest.getRequestURI()) && httpServletRequest.getMethod().equals("POST") && jcxProperties.getLoginProperties().getLoginCaptchaEnabled()) {
            // 校验验证码
            try {
                validate(httpServletRequest);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } catch (CaptchaException e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        } else {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }

    /**
     * 校验验证码逻辑
     *
     * @param httpServletRequest
     */
    private void validate(HttpServletRequest httpServletRequest) {
        String captchaCode = httpServletRequest.getParameter(jcxProperties.getLoginProperties().getParamCaptchaCode());
        String captchaKey = httpServletRequest.getParameter(jcxProperties.getLoginProperties().getParamCaptchaKey());
        if (StrUtil.isBlank(captchaCode) || StrUtil.isBlank(captchaKey)) {
            log.error(ErrorCode.CAPTCHA_ERROR.getMsg());
            throw CaptchaException.build(ErrorCode.CAPTCHA_ERROR.getMsg());
        }
        String redisCaptchaCode = redisService.getCacheObject(RedisKeys.createCodeToCaptcha(captchaKey));
        if (StrUtil.isBlank(redisCaptchaCode)) {
            log.error(ErrorCode.CAPTCHA_TIME_OUT.getMsg());
            throw CaptchaException.build(ErrorCode.CAPTCHA_TIME_OUT.getMsg());
        }
        if (!captchaCode.equals(redisCaptchaCode)) {
            log.error(ErrorCode.CAPTCHA_ERROR.getMsg());
            throw CaptchaException.build(ErrorCode.CAPTCHA_ERROR.getMsg());
        }
        // 若验证码正确，执行以下语句
        // 一次性使用
        redisService.deleteObject(RedisKeys.createCodeToCaptcha(captchaKey));
    }

}
